<template>
  <edit-dialog :centerDialogVisible="visible" :tilte="(isAdd ? '新增' : '编辑') + '维修单位'" @Cancel="handleCancel"
    @Submit="handleSubmit(goodsTypeFormRef)" :width="dialogWidth">
    <template #content>
      <div>
        <el-form ref="goodsTypeFormRef" :rules="rules" :model="form" label-width="150px">
          <el-form-item label="单位名称" prop="companyName">
            <el-input v-model="form.companyName" />
          </el-form-item>
          <el-form-item label="单位负责人" prop="head">
            <el-input v-model="form.head" />
          </el-form-item>
          <el-form-item label="负责人联系电话" prop="headPhone">
            <el-input v-model="form.headPhone" />
          </el-form-item>
          <!-- d）TOC加载责任机构时，可选择对应组织机构，其他机构不可选择默认当前用户所属组织架构 -->
          <!-- e）仅二级组织架构可选择责任机构，新增三级四级组织架构组织架构时，加载二级责任机构，置灰不可编辑 -->
          <!-- 1.toc的时候是树 -->
          <!-- 2.层级为2的才能选择，不为2的禁用 -->
          <!-- 3.层级3和4的时候，默认为2级机构，不能编辑 -->
          <template v-if="isAdd">
            <template v-if="userInfo && userInfo.organName === 'TOC'">
              <el-form-item label="责任单位" prop="respOrgId">
                <el-tree-select v-model="form.respOrgId" :props="defaultProps" default-expand-all :data="companyData"
                  :render-after-expand="false" />
              </el-form-item>
            </template>
            <template v-else>
              <el-form-item label="责任单位" prop="respOrgId">
                <el-input :disabled="true" v-model="form.respOrgId" />
              </el-form-item>
            </template>
          </template>
          <template v-else>
            <el-form-item label="责任单位" prop="respOrgId">
              <!-- c）仅二级组织架构可编辑责任机构。修改后责任机构后，需对应修改子级部门的责任机构 -->
              <!-- 编辑非一级目录，责任单位上级目录，且置灰不可编辑 -->
              <el-tree-select v-model="form.respOrgId" v-if="info?.level !== 1" :disabled="true" :props="defaultProps"
                default-expand-all :data="companyData" :render-after-expand="false" />
              <el-tree-select :value="''" v-else :disabled="true" :props="defaultProps" default-expand-all
                :data="companyData" :render-after-expand="false" />
              <!-- 编辑一级目录时，责任单位应该为空，且置灰不可编辑 -->
            </el-form-item>
          </template>
        </el-form>
      </div>
    </template>
  </edit-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive, defineProps, watch, nextTick, toRaw, computed } from 'vue'
import { useStore } from 'vuex'
import type { FormInstance, FormRules } from 'element-plus'
import { repCompanyAppend, repCompanyUpdate } from '@/api/rep/company'
import editDialog from '@/components/editDialog/index.vue'
import { ElMessage } from 'element-plus'
import { deepFn } from '@/utils/common'

interface RuleForm {
  companyName: string;
  head: string;
  headPhone: string;
  respOrgId: string;
}

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  isAdd: {
    type: Boolean,
    default: false,
  },
  info: {
    type: Object,
    default: () => null,
  },
  companyData: {
    type: Array,
    default: () => [],
  },
})

const emit = defineEmits(['cancel', 'ok'])

const defaultProps = {
  children: 'children',
  label: 'companyName',
  value: 'id',
}

const store = useStore()
// 弹窗标题
const dialogWidth = ref('460px')
const goodsTypeFormRef = ref<FormInstance>()
const userInfo = computed(() => store.state.user.userInfo)

const form = reactive<RuleForm>({
  companyName: '',
  head: '',
  headPhone: '',
  respOrgId: '',
})

const checkHeadPhone = (rule: any, value: any, callback: any) => {
  if (!value) return callback(new Error('请输入正确电话号码'))
  if (!/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(value)) return callback(new Error('电话格式不正确'))
  callback()
}

const checkCompanyName = (rule: any, value: any, callback: any) => {
  if (!value) return callback(new Error('请输入单位名称'));
  let flag = false;
  deepFn(toRaw(props.companyData), record => {
    if (props.isAdd) {
      if (record.companyName === value) {
        console.log(record.companyName === value)
        flag = true;
      }
    } else {
      if (props.info?.id && record.companyName === value && record.id !== props.info?.id) {
        console.log(record.companyName === value)
        flag = true;
      }
    }
  })
  console.log(flag, value, toRaw(props.companyData))
  if (flag) return callback(new Error('单位名称重复'));
  callback()
}

const rules = reactive<FormRules<RuleForm>>({
  companyName: [{ required: true, validator: checkCompanyName, trigger: 'change' }],
  head: [{ required: true, message: '请输入单位负责人', trigger: 'blur' }],
  respOrgId: [{ required: true, message: '请输入责任单位', trigger: 'blur' }],
  headPhone: [{ required: true, validator: checkHeadPhone, message: '请输入正确电话号码', trigger: 'blur' }],
})
const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let fetch = repCompanyAppend;
      const payload: any = { ...form };

      if (!props.isAdd) {
        fetch = repCompanyUpdate;
        payload.companyId = props.info.companyId;
        payload.mender = {
          id: userInfo.value.userId,
          name: userInfo.value.name,
          userName: userInfo.value.userName,
          organId: userInfo.value.organId || '',
          organName: userInfo.value.organName || ''
        }
      } else {
        payload.creator = {
          id: userInfo.value.userId,
          name: userInfo.value.name,
          userName: userInfo.value.userName,
          organId: userInfo.value.organId || '',
          organName: userInfo.value.organName || ''
        }
      }
      if (props.info?.companyId && props.isAdd) {
        payload.parentCompanyId = props.info?.companyId
      }
      console.log(payload);
      const res = await fetch(payload);

      if (res?.code === '1') {
        emit('ok')
        ElMessage.success(!props.isAdd ? '修改成功！' : '新增成功！');
      } else {
        ElMessage.error(res?.message || '操作失败，请重试！');
      }
      console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })
}

const handleCancel = () => {
  emit('cancel')
}

watch(() => props.visible, (val, oldVal) => {
  if (val && val !== oldVal) {
    nextTick(() => {
      if (props.info) {
        if (props.isAdd) {
          // 新增
          form.companyName = '';
          form.head = '';
          form.headPhone = '';
          // 层级3和4的时候，默认为2级机构
          form.respOrgId = props.info?.companyId || '';
        } else {
          // 编辑
          const info = toRaw(props.info);
          form.companyName = info?.companyName || '';
          form.head = info?.head || '';
          form.headPhone = info?.headPhone || '';
          // 编辑非一级目录时，责任单位应是上级目录。
          form.respOrgId = (props.info?.level === 1 ? props.info?.companyId : props.info?.respOrgId) || ''; // props.info?.companyId || '';
        }
      } else {
        form.companyName = '';
        form.head = '';
        form.headPhone = '';
      }
    })
  }
})
</script>